import { platformName } from '../config';

/**
 * 返回统一的url地址
 * @param {*} url 网页地址
 * @param {*} title 网页标题
 */
export function buildUrl(url, title) {
  return `/sub-packages/webview/index?url=${encodeURIComponent(url)}&title=${title}`;
}

/**
 * 判断是否是json字符串
 * @param {*} str 网页地址
 */
export function isJSONstring(str) {
  if (!str) return false;
  try {
    const tmp = JSON.parse(str);
    return !!tmp;
  } catch (err) {
    return false;
  }
}

/**
 * 格式化日期对象
 * @param {Date} date
 * @returns 2019/12/20 00:00:00
 */
export function formatDateToNormalStr(date) {
  if (date instanceof Date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();
    const formatNumber = n => {
      n = n.toString();
      return n[1] ? n : '0' + n;
    };

    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':');
  }
}

/**
 * 获取书籍分享链接
 * @param {String} bookid 书籍ID
 * @param {String} code 用户分享标识
 * @param {String} autoSecretCode 自动解锁标识
 */
export function getBookShareUrl(bookid, shareCode, autoSecretCode) {
  let str = '';
  if (bookid) {
    if (platformName === 'web') {
      str += `${window.location.origin}/#/pages/bookdetail/index?id=${bookid}`;
    } else {
      str += `https://h5.lantingshucheng.com/#/pages/bookdetail/index?id=${bookid}`;
    }
  }
  if (autoSecretCode) {
    str += `&pre_secret=${autoSecretCode}`;
  } else {
    if (shareCode) {
      str += `&share_code=${`${shareCode}@${Date.now()}`}`;
    }
  }
  if (str) {
    str += `&time=${Date.now()}`;
  }
  return str;
}

/**
 * 净化对象
 */
export function makeObjectClean(obj) {
  if (typeof obj == 'object' && Object.prototype.toString.call(obj).toLowerCase() == '[object object]' && !obj.length) {
    const result = {};
    Object.keys(obj).forEach(item => {
      if (obj[item]) {
        result[item] = obj[item];
      }
    });
    return result;
  }
  return obj;
}

/**
 * 是否未定义
 */
export function isDef(val) {
  return val !== null && val !== undefined;
}

/**
 * 是否为对象
 */
export function isObject(x) {
  const type = typeof x;
  return x !== null && (type === 'object' || type === 'function');
}

/**
 * 是否为空对象
 */
export function isEmptyObject(obj) {
  return isObject(obj) && !Object.keys(obj).length;
}

/**
 * 对象取值
 * @param {object} object 被取值对象
 * @param {string} object 取值路径
 * @param {*} defaultValue 默认值
 */
export function get(object, path, defaultValue = {}) {
  if (!object) {
    return defaultValue;
  }

  const keys = path.split('.');
  let result = object;

  keys.forEach(key => {
    result = isDef(result[key]) ? result[key] : {};
  });

  return isEmptyObject(result) ? defaultValue : result;
}

/**
 * url获取参数
 * @param {string} url 路径
 */
export function urlParse(url) {
  if (!url) return {};

  const obj = {};
  const reg = /[?&][^?&]+=[^?&]+/g;
  const arr = url.match(reg);
  if (arr) {
    arr.forEach(item => {
      let temArr = item.substring(1).split('=');
      let key = decodeURIComponent(temArr[0]);
      let value = decodeURIComponent(temArr[1]);
      obj[key] = value;
    });
  }
  return obj;
}

/**
 * 跳转函数
 * @param {string} url 路径
 */
export function navigate({ url }) {
  uni.navigateTo({
    url
  });
}

/**
 * 计算一组日期中连续天数的次数
 * @param {Array} arr
 */
export function continueDays(arr) {
  if (!(arr instanceof Array) || arr.length === 0) return 0;
  let date = new Date();
  let y = date.getFullYear();
  let m = date.getMonth() + 1;
  let d = date.getDate();
  let today = y + '/' + m + '/' + d;
  // 转时间戳
  function time(date) {
    return new Date(date);
  }
  // arr检测
  arr = arr.filter(item => {
    return time(item) < time(today);
  });
  let num = 0; //声明计数变量;
  let le = arr.length; //数组长度;
  // 日期时间戳相差一天则连续,此法虽笨,但实用;判断当前日期与最近一天
  if (time(today) - time(arr[le - 1]) == 86400000) {
    num = 2; //满足条件,连续2天;
    // 然后对数组循环判断,满足则num++;否则中断循环;
    for (let i = le; i > 0; i--) {
      if (time(arr[i - 1]) - time(arr[i - 2]) == 86400000) {
        num++;
      } else {
        break; // 如果只要找出所有连续的天数,不需要中断
      }
    }
    return num;
  } else {
    return 1;
  }
}

/**
 * 判断是否为iphoneX
 */
export function isIphoneX() {
  const systemInfo = uni.getSystemInfoSync();
  return systemInfo && ['iphonrx', 'iPhone X', 'iPhone XR', 'iPhone XS Max', 'iPhone 11', 'iPhone 12'].some(item => systemInfo.model.indexOf(item) > -1);
}

/**
 * 防抖函数
 */
export function debounce(func, wait) {
  let timer;
  return function () {
    const context = this;
    let args = arguments;

    if (timer) clearTimeout(timer);

    timer = setTimeout(() => {
      func.apply(context, args);
    }, wait);
  };
}

/**
 * @desc 函数节流
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param type 1 表时间戳版，2 表定时器版
 */
export function throttle(func, wait) {
  let previous = 0;
  return function () {
    let context = this;
    let args = arguments;
    let now = Date.now();
    if (now - previous > wait) {
      func.apply(context, args);
      previous = now;
    }
  };
}

/**
 * 动态修改TitleNView RedDot
 * @param {*} index
 * @param {*} show
 * @param {*} text
 */
export function setTitleNViewStyle(index, show, text) {
  let pages = getCurrentPages();
  let page = pages[pages.length - 1];
  // #ifdef APP-PLUS
  let currentWebview = page.$getAppWebview();
  if (show) {
    if (index === 0) {
      currentWebview.showTitleNViewButtonRedDot({ index: index, text: text });
    } else {
      currentWebview.setTitleNViewButtonBadge({ index: index, text: text });
    }
  } else {
    if (index === 0) {
      currentWebview.hideTitleNViewButtonRedDot({ index: index });
    } else {
      currentWebview.removeTitleNViewButtonBadge({ index: index });
    }
  }
  // #endif

  // #ifdef H5
  if (show) {
    if (index === 0) {
      const headBtnElement = document.querySelectorAll('.uni-page-head-hd .uni-page-head-btn')[1];
      if (headBtnElement) {
        headBtnElement.classList.add('uni-page-head-btn-red-dot');
      }
    } else {
      const headBtnElement = document.querySelector('.uni-page-head-ft .uni-page-head-btn');
      if (headBtnElement) {
        headBtnElement.classList.add('uni-page-head-btn-red-dot');
      }
    }
  } else {
    if (index === 0) {
      const headBtnElement = document.querySelector('.uni-page-head-ft .uni-page-head-btn');
      if (headBtnElement) {
        headBtnElement.classList.remove('uni-page-head-btn-red-dot');
      }
    } else {
      const redDotElement = document.querySelector('.uni-page-head-ft .uni-page-head-btn-red-dot');
      if (redDotElement) {
        redDotElement.classList.remove('uni-page-head-btn-red-dot');
      }
    }
  }
  // #endif
}

export function setPageTitle(title) {
  // #ifdef H5
  document.title = title;
  // #endif
  uni.setNavigationBarTitle({
    title
  });
}
